package com.zzedu.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzedu.common.cache.CacheNameContansts;
import com.zzedu.common.constant.Constants;
import com.zzedu.common.constant.UserConstants;
import com.zzedu.common.core.domain.entity.SysUser;
import com.zzedu.common.core.text.Convert;
import com.zzedu.common.utils.StringUtils;
import com.zzedu.system.domain.SysConfig;
import com.zzedu.system.mapper.SysConfigMapper;
import com.zzedu.system.service.ISysConfigService;
import org.apache.commons.collections4.MapUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 参数配置 服务层实现
 *
 * @author smarthome
 */
@Service
public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig> implements ISysConfigService {
    /**
     * 缓存名称
     */
    final String cacheName = CacheNameContansts.PARAMS_CACHE;

    /**
     * 查询参数配置信息
     *
     * @param configId 参数配置ID
     * @return 参数配置信息
     */
    @Override
    @Cacheable(value = cacheName, key = "#p0")
    public SysConfig selectConfigById(Long configId) {
        return getById(configId);
    }

    /**
     * 根据键名查询参数配置信息
     *
     * @param configKey 参数key
     * @return 参数键值
     */
    @Override
    public String selectConfigByKey(String configKey) {
        LambdaQueryWrapper<SysConfig> queryWrapper = Wrappers.lambdaQuery(SysConfig.class);
        queryWrapper.eq(SysConfig::getConfigKey, configKey);
        queryWrapper.last("limit 1");
        SysConfig sysConfig = getOne(queryWrapper);
        if (null != sysConfig) {
            return sysConfig.getConfigValue();
        }
        return null;
    }

    @Override
    @Cacheable(value = cacheName, key = "'value:'+#p0")
    public String selectConfigByKeyCache(String configKey) {
        LambdaQueryWrapper<SysConfig> queryWrapper = Wrappers.lambdaQuery(SysConfig.class);
        queryWrapper.eq(SysConfig::getConfigKey, configKey);
        queryWrapper.last("limit 1");
        SysConfig sysConfig = getOne(queryWrapper);
        if (null != sysConfig) {
            return sysConfig.getConfigValue();
        }
        return null;
    }

    @Override
    public SysConfig selectConfig(String configKey) {
        LambdaQueryWrapper<SysConfig> queryWrapper = Wrappers.lambdaQuery(SysConfig.class);
        queryWrapper.eq(SysConfig::getConfigKey, configKey);
        queryWrapper.last("limit 1");
        return getOne(queryWrapper);
    }

    /**
     * 查询参数配置列表
     *
     * @param config 参数配置信息
     * @return 参数配置集合
     */
    @Override
    public IPage<SysConfig> selectConfigList(IPage page, SysConfig config) {
        LambdaQueryWrapper<SysConfig> queryWrapper = Wrappers.lambdaQuery(SysConfig.class);
        queryWrapper.like(StringUtils.isNotBlank(config.getConfigKey()), SysConfig::getConfigKey, config.getConfigKey());
        queryWrapper.like(StringUtils.isNotBlank(config.getConfigName()), SysConfig::getConfigName, config.getConfigName());
        queryWrapper.eq(StringUtils.isNotBlank(config.getConfigType()), SysConfig::getConfigType, config.getConfigType());
        Map map = config.getParams();
        if (!MapUtils.isEmpty(map)) {
            if (map.containsKey("beginTime")) {
                queryWrapper.ge(SysConfig::getGmtCreate, MapUtils.getString(map, "beginTime"));
            }
            if (map.containsKey("endTime")) {
                queryWrapper.le(SysConfig::getGmtCreate, MapUtils.getString(map, "endTime"));
            }
        }
        queryWrapper.orderByDesc(SysConfig::getId);
        return page(page, queryWrapper);
    }

    /**
     * 新增参数配置
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    @CacheEvict(cacheNames = cacheName, allEntries = true)
    public int insertConfig(SysConfig config) {
        int row = baseMapper.insert(config);
        return row;
    }

    /**
     * 修改参数配置
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    @CacheEvict(cacheNames = cacheName, key = "'sys:params:'+#config.configKey")
    public int updateConfig(SysConfig config) {
        int row = baseMapper.updateById(config);
        return row;
    }

    /**
     * 批量删除参数配置对象
     *
     * @param configIds 需要删除的数据ID
     * @return 结果
     */
    @Override
    @CacheEvict(cacheNames = cacheName, allEntries = true)
    public void deleteConfigByIds(Long[] configIds) {
        removeBatchByIds(Arrays.stream(configIds).collect(Collectors.toList()));
    }

    /**
     * 加载参数缓存数据
     */
    @Override
    @CacheEvict(cacheNames = cacheName, allEntries = true)
    public void loadingConfigCache() {

    }

    /**
     * 清空参数缓存数据
     */
    @Override
    @CacheEvict(cacheNames = cacheName, allEntries = true)
    public void clearConfigCache() {

    }

    /**
     * 重置参数缓存数据
     */
    @Override
    @CacheEvict(cacheNames = cacheName, allEntries = true)
    public void resetConfigCache() {
    }

    /**
     * 校验参数键名是否唯一
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public boolean checkConfigKeyUnique(SysConfig config) {
        Long configId = StringUtils.isNull(config.getId()) ? -1L : config.getId();
        SysConfig info = selectConfig(config.getConfigKey());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != configId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 获取cache name
     *
     * @return 缓存名
     */
    private String getCacheName() {
        return Constants.SYS_CONFIG_CACHE;
    }


    /**
     * 获取验证码开关
     *
     * @return true开启，false关闭
     */
    @Override
    public boolean selectCaptchaEnabled() {
        String captchaEnabled = selectConfigByKey("sys.account.captchaEnabled");
        if (StringUtils.isEmpty(captchaEnabled)) {
            return true;
        }
        return Convert.toBool(captchaEnabled);
    }
}
